package cn.cdeden.knowledge.controller;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.oss.enumd.OssBucketOneEnum;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.SysPortalImages;
import cn.cdeden.knowledge.domain.dto.FileUserDto;
import cn.cdeden.knowledge.enums.StorageTypeEnum;
import cn.cdeden.knowledge.service.SysPortalImagesService;
import cn.cdeden.knowledge.service.dto.SysPortalImagesDto;
import cn.cdeden.knowledge.service.dto.SysPortalImagesQueryParam;
import cn.cdeden.resource.api.OssUploadService;
import cn.cdeden.resource.api.RemoteFileService;
import cn.cdeden.resource.api.domain.RemoteFile;
import cn.cdeden.resource.api.domain.RemoteFileDto;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author gjx
* @date 2024-09-26
**/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/sysPortalImages")
public class SysPortalImagesController {

    private final SysPortalImagesService sysPortalImagesService;

    @DubboReference(check = false)
    private final RemoteFileService remoteFileService;


    @GetMapping
//    @Log("查询企业门户的图片配置")
    public TableDataInfo<SysPortalImagesDto> query(SysPortalImagesQueryParam query, @PageableDefault(sort = {"create_time"},direction = Sort.Direction.DESC) Pageable pageable){
        TableDataInfo<SysPortalImagesDto> info = sysPortalImagesService.queryAll(query,pageable);
        return info;
    }

    @PostMapping
//    @Log("新增企业门户图片配置")
    @Transactional(rollbackFor = Exception.class)
    public R create(@Validated @ModelAttribute  SysPortalImagesDto resources){
        MultipartFile file = resources.getFile();
//        Storage storage = fileStorageUtils.create(user.getId().toString(), user.getUsername(), StorageFolderTypeEnum.PUBLIC_BUCKET.getCode(), file, FileEnums.SYSTEM_SETTINGS, null);
        RemoteFile upload = null;
        try {
            RemoteFileDto build = RemoteFileDto.builder().name(resources.getName())
                .file(file.getBytes())
                .bucketName(OssBucketOneEnum
                    .PUBLIC_IMAGES.getCode())
                .originalFilename(file.getOriginalFilename())
                .moduleType(OssModuleType.Enterprise).build();
            upload = remoteFileService.upload(build);
        }catch (IOException e ){
            throw new RuntimeException("文件上传失败");
        }
        if (upload != null) {
            String path = upload.getUrl();
            Long storageId = upload.getOssId();
            resources.setUrl(path);
            resources.setStorageId(storageId);
            return R.ok(sysPortalImagesService.insert(resources));
        }else {
            return R.fail();
        }
    }

    @PutMapping
//    @Log("修改企业门户图片配置")
    @Transactional(rollbackFor = Exception.class)
    public R update(@Validated @RequestBody SysPortalImagesDto resources){
        MultipartFile file = resources.getFile();
        if (!file.isEmpty()) {
            RemoteFile upload = null;
            try {
                RemoteFileDto build = RemoteFileDto.builder().name(resources.getName())
                    .file(file.getBytes())
                    .bucketName(OssBucketOneEnum
                        .PUBLIC_IMAGES.getCode())
                    .originalFilename(file.getOriginalFilename())
                    .moduleType(OssModuleType.Enterprise).build();
                upload = remoteFileService.upload(build);
            }catch (IOException e ){
                throw new RuntimeException("文件上传失败");
            }
            if(upload != null){
                resources.setUrl(upload.getUrl());
                resources.setStorageId(upload.getOssId());
                return R.ok(sysPortalImagesService.updateById(resources));
            }else {
                return R.fail();
            }

        }else {
            return R.ok(sysPortalImagesService.updateById(resources));
        }
    }

    @DeleteMapping
//    @Log("删除企业门户图片配置")
    @Transactional(rollbackFor = Exception.class)
    public R delete(@RequestBody Set<Long> ids) {
        for (Long id : ids) {
            SysPortalImages byId = sysPortalImagesService.getById(id);
            if (byId != null){
                Long storageId = byId.getStorageId();
                sysPortalImagesService.list(new QueryWrapper<SysPortalImages>().eq("id", id));
                remoteFileService.deleteWithValidByIds(List.of(storageId),false);
                return R.ok(sysPortalImagesService.deleteByIds(ids));
            }
        }
        return R.ok();
    }


    @GetMapping("/get-all-images")
//    @Log("查询全部轮播图")
//    @PreAuthorize("@el.check('sysPortalImages:list')")
    public R<List<SysPortalImages>> getAllImages() {
        return R.ok(sysPortalImagesService.list());
    }





    /*
    @Log("导出SysPortalImagesService")
    @ApiOperation("导出SysPortalImagesService")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('sysPortalImages:list')")
    public void download(HttpServletResponse response, SysPortalImagesQueryParam query) throws IOException {
        sysPortalImagesService.download(sysPortalImagesService.queryAll(query), response);
    }*/

}
